package cn.lhl.flowable.workflow;

import org.flowable.engine.*;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class LCDuoRenHuiQian {
    private static String deploymentName = "LCDuoRenHuiQian";
    @Resource
    private ProcessEngine processEngine;
    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;
    @Resource
    private HistoryService historyService;


    /**
     * 部署
     */
    public void Deployment() {
        //获取Flowable服务
        RepositoryService repositoryService = processEngine.getRepositoryService();

        // 查询deploymentName("LCDuoRenHuiQian")的
        Deployment singleResult = repositoryService.createDeploymentQuery().deploymentName(deploymentName).singleResult();

        if (null != singleResult) {
            //删除部署的流程  会删除流程和部署的信息  true 加上历史 和任务
            repositoryService.deleteDeployment(singleResult.getId(), true);

            //更新
            // repositoryService.changeDeploymentParentDeploymentId(singleResult.getId());

        }


        //部署流程定义  会创建流程 和部署信息
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("processes/多人会签.bpmn20.xml") //资源路径
                .name(deploymentName)//javaboy的工作流名称
                .category("会签")//javaboy的工作流分类
                .key("会签_javaboy的工作流key")//javaboy的工作流key
                .deploy();


        // ===========================================
        //查询全部的流程
        List<ProcessDefinition> list1 = repositoryService.createProcessDefinitionQuery().list();
        //遍历方法二：
        System.out.println("全部的流程>>>>>>>" + list1.size());
        list1.forEach(System.out::println);
        //System.out.println("全部的流程>>>>>>>"+ list1.size());

        //查询全部的 部署信息
        List<Deployment> list = repositoryService.createDeploymentQuery().list();

        System.out.println("全部的部署信息>>>>>>>" + list.size());
        list.forEach(System.out::println);

        //通过资源name查流程
        List<ProcessDefinition> processDefinitionList = repositoryService.createProcessDefinitionQuery()
                .processDefinitionResourceName("processes/多人会签.bpmn20.xml")
                .list();

        System.out.println("通过资源name查流程 >>>>" + processDefinitionList.size());
        processDefinitionList.forEach(System.out::println);


    }


    /**
     * 启动流程
     *
     */
    @Transactional
    public void start() {
        List<String> persons = Arrays.asList("use1","use2","use3");
        Map<String, Object> variables =new HashMap<>();
        String candidateGroupkey="风控人员组";
        variables.put(candidateGroupkey,"mmmmm");
        variables.put("assigneeList",persons);

        // LCQingJia是流程xml文件的 process id
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("huiqian_shenpi", variables);
        String pid = processInstance.getId();
        System.out.println("pid:" + pid);
    }


    /**
     * 部门经理查看任务
     *
     * @return
     */
    public List<String> daiban() {
        String candidateGroupkey="风控人员组";
        String candidateGroupkval="mmmmm"; //elementVariable
        List<Task> tasks = taskService.createTaskQuery()
                .taskCandidateGroup(candidateGroupkval)
                //.taskVariableValueEquals("person","use3")
                //.taskVariableExists("su")
                .orderByTaskCreateTime() // 按照任务创建时间
                .desc() // 倒序排列
                .list();

        List<Task> task22 = taskService.createTaskQuery().taskAssignee("use3").list();
        System.out.println("taskAssignee 查到>>" + task22);
        if ( task22.size()>0){

            //任务手动分发 其他人
            taskService.setAssignee(task22.get(0).getId(), "use2");
            taskService.setAssignee(task22.get(0).getId(), "use1");

            List<Task> task223 = taskService.createTaskQuery().taskAssignee("use3").list();
            System.out.println("taskAssignee 查到分走后的>>" + task223);

            taskService.setAssignee(task22.get(0).getId(), "use3");
            List<Task> task22333 = taskService.createTaskQuery().taskAssignee("use3").list();
            System.out.println("taskAssignee 查到分走后的 再分回来的>>" + task22333);

        }


        List<String> retList = new ArrayList<>();
        for (int i = 0; i < tasks.size(); i++) {
            Task task = tasks.get(i);

            //根据任务Id查询特定流程实例的变量
            Map<String, Object> processVariables = taskService.getVariables(task.getId());
            System.out.println("根据任务Id查询特定流程实例的变量>>" + processVariables);

            String msg = String.format("pid:%s,task_name:%s,tid:%s，task_key:%s,Variables:%s",
                    task.getProcessInstanceId(),
                    task.getName(),
                    task.getId(),
                    task.getTaskDefinitionKey(),
                    processVariables
            );

            retList.add(msg);
        }
        return retList;
    }

    /**
     * 同意 通过
     */
    public void tongyi( String assignee ) {
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(assignee)
                .orderByTaskCreateTime() // 按照任务创建时间
                .desc() // 倒序排列
                .list();

        if (tasks.size() <= 0) {
            System.out.println("无任务tasks");
            return;
        }

        Map variables = new HashMap<String, Object>();
        // approved 是流程定义中的值，不能改动
        variables.put("excl_approved", 1);

        String tid = tasks.get(0).getId();
        // 传入tid
        taskService.complete(tid, variables);
        System.out.println("tongyi>>>tid:" + tid);
    }


    public void chaLiShiLiuCheng() {

        System.out.println("历史的流程>>>>");
        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().finished()
                .orderByProcessInstanceEndTime()
                .desc()
                .list();

        list.forEach(System.out::println);

    }

    public void chaLiShiTask(String candidateGroup) {
        System.out.println("历史的Task>>>>");
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().finished().taskCandidateGroup(candidateGroup)
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .list();

        list.forEach(System.out::println);

    }
    /**
     * 部门经理拒绝
     */
    public void jujue() {
//        获取最新的task id
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("managers")
                .orderByTaskCreateTime()
                .desc()
                .list();
        String taskId = tasks.get(0).getId();
        Map variables = new HashMap<String, Object>();
        variables.put("approved", false);
//        传入tid
        taskService.complete(taskId, variables);
    }





}
